package yannan.voiplock4ble;


import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocationClient;
import com.github.ybq.android.spinkit.style.ThreeBounce;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import yannan.voiplock4ble.adapter.AddDevicesAdapter;
import yannan.voiplock4ble.adapter.base.RecyclerViewBaseAdapter;
import yannan.voiplock4ble.base.Content;
import yannan.voiplock4ble.base.LoggedBaseActivity;
import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.base.MyEnum;
import yannan.voiplock4ble.bean.LockBean;
import yannan.voiplock4ble.bean.LockBeanDao;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.daomanager.LockBeanDaoManager;
import yannan.voiplock4ble.eventbus.AddLockEvent;
import yannan.voiplock4ble.eventbus.BaseEventMsg;
import yannan.voiplock4ble.eventbus.MainMsg;
import yannan.voiplock4ble.eventbus.SearchLockBleMsg;
import yannan.voiplock4ble.service.ble.BleService;
import yannan.voiplock4ble.service.ble.BleUtils;
import yannan.voiplock4ble.task.UPLocationTask;
import yannan.voiplock4ble.utils.OperLockUtils;
import yannan.voiplock4ble.utils.PopShowUtils;
import yannan.voiplock4ble.utils.ToastUtils;
import yannan.voiplock4ble.view.RecyclerSupportViewEmpty;

/**
 * 说明：添加门锁
 * 作者：mainTel
 * 时间：2016/8/24 09:39
 * 备注：
 */
@Content(R.layout.activity_search_lock)
public class SearchLockActivity extends LoggedBaseActivity implements View.OnClickListener, RecyclerViewBaseAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {
    @Bind(R.id.rl_devices_search)
    RecyclerSupportViewEmpty rl_devices_search;
    @Bind(R.id.pro_search)
    ProgressBar pro_search;
    @Bind(R.id.rl_search)
    RelativeLayout rl_search;
    @Bind(R.id.swip_refresh)
    SwipeRefreshLayout swip_refresh;
    @Bind(R.id.lv_lock_record_empty_view)
    ScrollView lv_lock_record_empty_view;
    @Bind(R.id.lv_lock_record_empty_textview)
    TextView lv_lock_record_empty_textview;

    AddDevicesAdapter addDevicesAdapter;
    BluetoothDevice connectDevice;
    UPLocationTask upLoadAddressTask;
    private AMapLocationClient mLocationClient;
    private AlertDialog dialog;

    @Override
    public void initData() {
        setTitleTheme(TitleTheme.TOOLBAR_THEME_COMMON, "添加门锁");
        swip_refresh.setOnRefreshListener(this);
        lv_lock_record_empty_textview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!swip_refresh.isRefreshing()) {
                    EventBus.getDefault().post(BleService.BLE_MSG_START_SEARCH_TRUE);
                    rl_search.setVisibility(View.VISIBLE);
                    swip_refresh.setRefreshing(true);
                }
            }
        });
        //发消息开始搜索蓝牙设备
        EventBus.getDefault().post(BleService.BLE_MSG_START_SEARCH_TRUE);
        addDevicesAdapter = new AddDevicesAdapter(new ArrayList<BluetoothDevice>(), mContext);
        rl_devices_search.setLayoutManager(new LinearLayoutManager(mContext));
        rl_devices_search.setEmptyView(lv_lock_record_empty_view);
        rl_devices_search.setAdapter(addDevicesAdapter);
        addDevicesAdapter.setOnItemClickListener(this);
        mLocationClient = new AMapLocationClient(getApplicationContext());
        upLoadAddressTask = new UPLocationTask(mLocationClient);
        upLoadAddressTask.start();
        ThreeBounce doubleBounce = new ThreeBounce();
        pro_search.setIndeterminateDrawable(doubleBounce);
    }

    @Override
    public void onRefresh() {
        lockMap.clear();
        addDevicesAdapter.clear();
        EventBus.getDefault().post(BleService.BLE_MSG_START_SEARCH_TRUE);
        rl_search.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AddLockEvent msg) {
        switch (msg.msgWhat) {
            case STOP_SEACH_BLE:
                rl_search.setVisibility(View.GONE);
                swip_refresh.setRefreshing(false);
                break;
        }
    }

    Map<String, String> lockMap = new HashMap<>();

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BluetoothDevice device) {
        if (lockMap.get(device.getAddress()) == null) {
            addDevicesAdapter.addItem(device);
            lockMap.put(device.getAddress(), device.getName());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BaseEventMsg msg) {
        if (msg instanceof SearchLockBleMsg) {
            SearchLockBleMsg searchLockBleMsg = (SearchLockBleMsg) msg;
            if (searchLockBleMsg.permissions != -1) {
                isConnect = false;
                dimssProgress();
                ToastUtils.showToast(mContext, "连接成功");
                if (searchLockBleMsg.permissions == 2) {
                    showHintPop(true);
                } else if (searchLockBleMsg.permissions == 1) {
                    showHintPop(false);
                } else {
                    //对比本地是否有此门锁，如果有不做提示 没有 提示添加名字并存入本地
                    MyApplication.getInterface().mConnectLock.lockserialId = connectDevice.getName();
                    LockBean lockBean = null;
                    try {
                        lockBean = DaoUtils.getDao(LockBeanDaoManager.class).getQueryBuilder()
                                .where(LockBeanDao.Properties.LockserialId.eq(connectDevice.getName()))
                                .build().list().get(0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (lockBean == null) {
                        lockBean = new LockBean();
                        editName(lockBean);
                    } else {
                        getLockInfoBle();
                        upLoadAddressTask.setLockserialId(lockBean.lockserialId);
                        //跳转到 开锁记录
                        goToLockRecord(lockBean.lockserialId);
                    }
                }
            }
        }
    }


    /**
     * 提示用户没有权限
     */
    private void showHintPop(boolean isYK) {
        if (isYK) {
            PopShowUtils.showCommonDialog(mContext, "您还不是该门锁指静脉用户或者您不是管理员，无法对门锁进行设置或查看数据，是否立即注册成为管理员？", "不用了", "去注册", false,
                    new PopShowUtils.IDialogCommonListener() {
                        @Override
                        public void onClick(int direction) {
                            if (direction == PopShowUtils.COMMON_DIALOG_LEFT) { //取消 断开连接
                                BleService.getBleService().disConnect();
                                ToastUtils.showToast(mContext, "门锁已断开");
                                //断开连接不中断位置上传
                                //upLoadAddressTask.stopLocation();
                            } else { //去注册
                                Intent intent = new Intent(mContext, AddPwdOrVeinActivity.class);
                                intent.putExtra("type", "vein");
                                intent.putExtra("isFromSearch", true);
                                startActivityForResult(intent, FIRST_REGISTER);
                            }
                        }
                    });
        } else {
            PopShowUtils.showCommonDialog(mContext,
                    "您还不是该门锁的管理员，无法对门锁进行设置或查看数据，请更换手机号或者联系管理员！",
                    null, "确定", false,
                    new PopShowUtils.IDialogCommonListener() {
                        @Override
                        public void onClick(int direction) {
                            BleService.getBleService().disConnect();
                            ToastUtils.showToast(mContext, "门锁已断开");
                            upLoadAddressTask.stopLocation();
                        }
                    });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SearchLockActivity");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SearchLockActivity");
        MobclickAgent.onPause(this);
    }

    /**
     * 设置门锁名字
     *
     * @param lockBean
     */
    private void editName(final LockBean lockBean) {
        PopShowUtils.editLocalLockName(mContext, new PopShowUtils.IOnEditName() {
            @Override
            public void onChange(String msg) {
                //修改成功 存入本地
                if (msg.equals(""))
                    msg = connectDevice.getName();
                lockBean.lockName = msg;
                lockBean.userId = MyApplication.getInterface().userBean.userId;
                lockBean.lockserialId = connectDevice.getName();
                lockBean.mac = connectDevice.getAddress();
                lockBean.userPermission = MyApplication.getInterface().mConnectLock.phoneMatchType;
                try {
                    DaoUtils.getDao(LockBeanDaoManager.class).insertOrReplace(lockBean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                getLockInfoBle();
                upLoadAddressTask.setLockserialId(lockBean.lockserialId);
                OperLockUtils.bindLock(lockBean, 0);
                //跳转到开锁记录
                goToLockRecord(lockBean.lockserialId);
            }
        });
    }

    private void goToLockRecord(String lockserial) {
        finish();
        isok = false;
        EventBus.getDefault().post(new MainMsg(MainMsg.FROM_SEARCHLOCKACTIVITY, lockserial));
    }

    /**
     * 从门锁获取信息
     */
    private void getLockInfoBle() {
        if (MyApplication.getInterface().mConnectLock != null)
            BleService.getBleService().sendOrder(BleUtils.getElec(
                    MyApplication.getInterface().mConnectLock.contentToken));
    }


    @Override
    public void onItemClick(View view, final int poi) {
        BluetoothDevice device = addDevicesAdapter.getItemByPosition(poi);
        // TODO: 2016/11/22 链接 判断权限 设置别名 绑定门锁 存入本地 跳转入开锁记录页面
        connectDevice = device;
        EventBus.getDefault().post(new SearchLockBleMsg(device)); //发送消息到BleService
        showConnectPro();
//        if (!upLoadAddressTask.isAlive()) {
//            upLoadAddressTask.start();
//        }
        //每次点击是否都需要重启一个上传位置的线程
//        else {
//            upLoadAddressTask=new UPLocationTask(mLocationClient);
//            upLoadAddressTask.start();
//        }
    }

    private void showConnectPro() {
//        showProgress();
        showTips();
        isConnect = false;
        mhandler.sendEmptyMessageDelayed(STOP_CONNECT_PRO, 8000);
    }

    /**
     * 提示需要同意在可以连接成功
     */
    private void showTips() {
        if (dialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            ImageView imageView = new ImageView(this);
            imageView.setImageDrawable(getResources().getDrawable(R.drawable.image_bind_lock));
            builder.setView(imageView);
            dialog = builder.create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(false);
        }
        dialog.show();
    }

    boolean isConnect;
    final static int STOP_CONNECT_PRO = 12350;

    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case STOP_CONNECT_PRO:
                    if (!isConnect) {
                        dimssProgress();
                        dialog.dismiss();
                        if (MyApplication.getInterface().mConnectLock==null) {
                            ToastUtils.showToast(SearchLockActivity.this, "连接不成功，请重新连接");
                        } else {
                            ToastUtils.showToast(SearchLockActivity.this,"连接成功");
                        }
//                        BleService.getBleService().disConnect();
                    }
                    break;
            }
        }
    };

    public static int FIRST_REGISTER = 1002;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FIRST_REGISTER && resultCode == RESULT_OK) {
            if (data.getBooleanExtra("addVeinKeySuc", false)) {
                BleService.getBleService().sendOrder(BleUtils.connectLock(
                        MyApplication.getInterface().userBean.userAccount.getBytes()
                ));
            }
        }
    }

    boolean isok = true;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isok) {
            upLoadAddressTask.stopLocation();
        }
        if (dialog != null) {
            dialog.dismiss();
        }
    }

}
